<!--
  * 码牌表
  *
  * @Author:    zhoujk
  * @Date:      2025-01-26 06:40:43
-->
<template>
  <a-modal :title="'添加码牌'" :width="600" :open="visibleFlag" @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
    <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
      <a-row>
        <a-col :span="12">
          <a-form-item label="前缀" name="codePrefix">
            <a-input style="width: 90%" v-model:value="form.codePrefix" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="总长度" name="length">
            <a-input-number style="width: 90%" v-model:value="form.length" :min="0" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="起止号码" name="codeNumRange" class="range-inputs-wrapper">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-input-number
                  @change="formRef.validateFields(['codeNumRange'])"
                  style="width: 100%"
                  v-model:value="form.codeNumBegin"
                  :min="0"
                  placeholder="请输入"
                />
              </a-col>
              <a-col :span="12">
                <a-input-number
                  @change="formRef.validateFields(['codeNumRange'])"
                  style="width: 100%"
                  v-model:value="form.codeNumEnd"
                  :min="0"
                  placeholder="请输入"
                />
              </a-col>
            </a-row>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="默认密码" name="defaultPwd">
            <a-input style="width: 90%" v-model:value="form.defaultPwd" placeholder="请输入" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <template #footer>
      <div class="footer-actions">
        <a-space>
          <a-button type="primary" style="background-color: #f39923; border: 1px solid #f39923" @click="onValidate" v-privilege="'code:insert_check'"
            >验证
          </a-button>
        </a-space>
        <a-space>
          <a-button @click="onClose">取消</a-button>
          <a-button type="primary" @click="onSubmit">保存</a-button>
        </a-space>
      </div>
    </template>
  </a-modal>
</template>
<script setup>
  import { nextTick, reactive, ref } from 'vue'
  import _ from 'lodash'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { codeApi } from '/@/api/business/b-agent/code/code-api'
  import { smartSentry } from '/@/lib/smart-sentry'
  import { useUserStore } from '/@/store/modules/system/user'

  console.log('useUserStore===>', useUserStore().userInfo)

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList'])

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false)

  function show(rowData) {
    Object.assign(form, formDefault)
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData)
    }
    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    // if (form.status && form.status.length > 0) {
    //   form.status = form.status.map((e) => e.valueCode);
    // }
    visibleFlag.value = true
    nextTick(() => {
      formRef.value.clearValidate()
    })
  }

  function onClose() {
    Object.assign(form, formDefault)
    visibleFlag.value = false
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref()

  const formDefault = {
    codePrefix: undefined, //码牌前缀
    length: undefined, //总长度
    codeNumBegin: undefined, //起始号码
    codeNumEnd: undefined, //截至号码
    defaultPwd: undefined, //默认密码
  }

  let form = reactive({ ...formDefault })

  const rules = {
    codePrefix: [
      { required: true, message: '码牌前缀 必填' },
      { type: 'string', max: 23, message: '码牌前缀最大23字' },
    ],
    length: [
      { required: true, message: '总长度 必填' },
      { type: 'number', min: 1, max: 24, message: '总长度 范围1-24' },
    ],
    // 合并起止号码的规则到同一个键名
    codeNumRange: [
      {
        validator: () => {
          const { codeNumBegin, codeNumEnd } = form
          if (!codeNumBegin || !codeNumEnd) return Promise.reject('起止号码 必填')
          // 类型校验
          if (typeof codeNumBegin !== 'number' || typeof codeNumEnd !== 'number') {
            return Promise.reject('必须输入有效数字')
          }
          // 逻辑关系校验
          if (codeNumEnd <= codeNumBegin) {
            return Promise.reject(new Error('结束号码必须大于起始号码'))
          }
          return Promise.resolve()
        },
      },
    ],
    defaultPwd: [{ required: true, message: '默认密码 必填' }],
  }

  async function onValidate() {
    try {
      await formRef.value.validateFields(['codePrefix', 'length', 'codeNumRange'])
      const res = await codeApi.insertCheck({ ...form, agentId: useUserStore().userInfo.oUserId })
      message.success('验证成功')
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields()
      save()
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show()
    try {
      await codeApi.insert({ ...form, agentId: useUserStore().userInfo.oUserId })
      message.success('操作成功')
      emits('reloadList')
      onClose()
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }

  defineExpose({
    show,
  })
</script>

<style lang="less" scoped>
  :deep(.range-inputs-wrapper) {
    display: flex;
    justify-content: space-between;
    width: 90%;

    /* 处理输入框间距 */

    .ant-input {
      width: calc(50% - 8px) !important;
      margin-right: 16px;

      &:last-child {
        margin-right: 0;
      }
    }
  }

  .footer-actions {
    display: flex;
    justify-content: space-between;
    width: 100%;
    align-items: center; /* 垂直居中 */
  }

  /* 如果使用 Ant Design 的 a-space 组件 */
  :deep(.footer-actions .ant-space) {
    flex-shrink: 0; /* 防止按钮组被压缩 */
  }
</style>
